package com.gxan.web.renshi;


import com.alibaba.fastjson.JSONObject;
import com.gxan.utils.FileUtils;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/UploadServlet")
@MultipartConfig //这个Servlet 请求是携带文件的  必须
public class UploadServlet2 extends HttpServlet {
    //练习+思考怎么解决文件名冲突
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part headImg = request.getPart("file");
        String fileName = headImg.getSubmittedFileName();
        //唯一
        fileName = FileUtils.newFileName("",fileName);
        HttpSession httpSession = request.getSession();
        Map map = new HashMap();
        try {
            String realPath = request.getServletContext().getRealPath("");
            String path = "image/"+fileName;
            String absolutePath = realPath+path;
            headImg.write(absolutePath);
            map.put("code",0);
            map.put("msg","success");
            map.put("uri",fileName);
            response.getWriter().write(JSONObject.toJSONString(map));
        }catch (FileNotFoundException e){
            e.printStackTrace();
            map.put("code",-1);
            map.put("msg","文件未找到");
            response.getWriter().write(JSONObject.toJSONString(map));
        }

    }
}
